#coding:utf8
import cmd, socket, traceback, threading, time
import sys

class ChatClient(cmd.Cmd):
    ''' chat client '''
    def __init__(self, host='localhost', port=10001):
        cmd.Cmd.__init__(self)
        self.host = host
        self.port = port
        self.sock = ''
        self.prompt =  'chatClient>'
        self.completekey='\n'
        self.name = ''

    def do_connect(self, line):
        s = socket.socket()
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.connect((self.host, self.port))
        s.settimeout(0.1)
        print 'u are connected, and you can input your name, example: name butcher'
        self.sock = s

    def do_name(self, line):
        if not self.sock:
            print 'please connect first'
        line = line.strip()
        self.prompt = '%s> ' % line
        self.sock.send('name\t%s' % line)
        self.name = line
        #print 'name', line
        t = threading.Thread(target=ChatClient.continue_read, args=(self,))
        t.setDaemon(True)
        t.start()

    def do_msg(self, line):
        if not line:
            print 'input error, msg is empty, check it and reinput'
        if line:
            self.sock.send('msg\t%s' % line)

    def do_show(self, line):
        if not self.name:
            print 'please set your name first'
        self.sock.send('show\ttmp')
        #print 'show'

    def do_pm(self, line):
        if not line:
            print 'input error, msg is empty, check it and reinput'
        if line:
            self.sock.send('pm\t%s' % line)

    @staticmethod
    def continue_read(chatclient):
        while 1:
            try:
                msg = chatclient.sock.recv(1024)
                if msg:
                    print msg
                    sys.stdout.write(chatclient.prompt)
                    sys.stdout.flush()
                else:
                    break
            except socket.timeout:
                pass
            except:
                traceback.print_exc()
            time.sleep(1)
        print 'exit thread', threading.currentThread().getName()

    def do_EOF(self, line):
        if self.sock:
            self.sock.close()
        return True

if __name__=='__main__':
    ChatClient().cmdloop()